package com.fund.order.utils;

import com.fund.common.enums.TradeType;
import com.fund.order.constants.OrderConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

@Component
public class OrderNumberGenerator {

    static StringRedisTemplate redisTemplate;

    @Autowired
    public void setRedisTemplate(StringRedisTemplate redisTemplate) {
        OrderNumberGenerator.redisTemplate = redisTemplate;
    }

    public static String getNewOrderNumber(TradeType tradeType) {
        //获取时间戳
        ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
        ZonedDateTime zonedDateTime = ZonedDateTime.of(2025, 1,
                1, 0, 0, 0, 0, ZoneOffset.UTC);
        long timestamp = now.toEpochSecond() - zonedDateTime.toEpochSecond();
        //获取今日日期，作为key的区分
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String today = now.format(formatter);
        //查询序列号
        String key = OrderConstant.SERIAL_NUMBER_PREFIX + today;
        Long serialNumber = redisTemplate.opsForValue().increment(key);
        long orderNumber = timestamp << 32 | serialNumber;
        String orderPrefix = tradeType == TradeType.PURCHASE ? OrderConstant.PURCHASE_PREFIX : OrderConstant.REDEMPTION_PREFIX;
        return orderPrefix + orderNumber;
    }
}
